#include "BlackHole.h"
#include "Object.h"
#include "Field.h"
#include "Controller.h"

void BlackHole::update( int ) {
    if( strength <= 0 ) {
        explode();
        return getField()->destroy( getX(), getY() );
    }
    if( currentCd <= 0 ) {
        currentCd = cooldown;
        spawn();
    } else {
        currentCd--;
    }
    /*if( getUpdateStatus() ) {
        setUpdateStatus( false );
        paint();
    }*/
}

void BlackHole::spawn() {
    int defaultRate = spawnRate;
    for( int i = 0; i < spawnRate && i < 8; i++ ) {
        int x = getX(), y = getY();
        switch( i ){
            case     NORTH :         y -= 1; break;
            case NORTHEAST : x += 1; y -= 1; break;
            case      EAST : x += 1;         break;
            case SOUTHEAST : x += 1; y += 1; break;
            case     SOUTH :         y += 1; break;
            case SOUTHWEST : x -= 1; y += 1; break;
            case      WEST : x -= 1;         break;
            case NORTHWEST : x -= 1; y -= 1; break;
            default: return; break;
        }
        if( !getField()->spawnObject( x, y, new Gangster( x, y, getField(), true,
                                                         team,
                                                         randController(),
                                                         2, 1, false, false, true,
                                                         2*cooldown )) ) {
            spawnRate++;
        }
    }
    spawnRate = defaultRate;
}

void BlackHole::damage( int i ) {
    strength -= i;
}

void BlackHole::explode() {
    for( Direction i = NORTH; i < NONE; ++i ) {
        int x = getX(), y = getY();
        switch( i ){
            case     NORTH :         y -= 1; break;
            case NORTHEAST : x += 1; y -= 1; break;
            case      EAST : x += 1;         break;
            case SOUTHEAST : x += 1; y += 1; break;
            case     SOUTH :         y += 1; break;
            case SOUTHWEST : x -= 1; y += 1; break;
            case      WEST : x -= 1;         break;
            case NORTHWEST : x -= 1; y -= 1; break;
            default: return; break;
        }
        if( !(getField()->spawnObject( x, y, new Bullet( x, y, getField(), true, i, 5 )) ) ) {
            getField()->objectAt( x, y )->damage( Bullet::DMGVALUE );
        }
    }
}

void BlackHole::save( ofstream* save, ofstream* config ) {
    (*save) << BLACKHOLECHAR;
    (*config) << BLACKHOLECHAR << cooldown << endl
              << spawnRate << endl << currentCd << endl
              << strength << endl;
    switch( getTeam() ){
        case( TEAMENUM ): (*config) << char(TEAMENUMCHAR);  break;
        case( TEAMID ):   (*config) << char(TEAMIDCHAR);    break;
        case( TEAMDEMON ):(*config) << char(TEAMDEMONCHAR); break;
        default:          (*config) << char(TEAMENUMCHAR);  break;
    }
    (*config) << endl;
}
